package com.xiaolong.web.serializer;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateSerializer implements ObjectSerializer {
    public static final LocalDateSerializer INSTANCE = new LocalDateSerializer();
    public static final String FORMAT_DATE = "yyyy-MM-dd";
    public static final String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    public static final DateTimeFormatter LOCAL_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter LOCAL_DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public LocalDateSerializer() {
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object == null) {
            out.writeNull();
        } else {
            if (object instanceof LocalDate) {
                LocalDate localDate = (LocalDate)object;
                out.writeString(localDate.format(LOCAL_DATE_FORMAT));
            } else if (object instanceof LocalDateTime) {
                LocalDateTime localDateTime = (LocalDateTime)object;
                out.writeString(localDateTime.format(LOCAL_DATE_TIME_FORMAT));
            } else {
                out.writeString(object.toString());
            }

        }
    }
}
